import org.codehaus.jettison.json.JSONException;
import org.codehaus.jettison.json.JSONObject;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

public class WechatGroupBot {
    private static final String APPID = "你的AppID";
    private static final String SECRET = "你的Secret";
    private static final String TO_USER = "用户的OpenID列表，多个OpenID之间用逗号隔开";
    private static final String TO_TYPE = "2"; // 群聊消息，类型为2  
    private static final String URL = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=";

    public static void main(String[] args) throws Exception {
        // 获取access_token  
        String accessToken = getAccessToken();
        if (accessToken == null) {
            System.out.println("获取access_token失败");
            return;
        }

        // 读取标准输入的消息内容  
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
        String message = reader.readLine();

        // 构建请求参数  
        Map<String, String> params = new HashMap<>();
        params.put("access_token", accessToken);
        params.put("touser", TO_USER);
        params.put("msgtype", "text");
        params.put("text", "{\"content\":\"" + message + "\"}");
        params.put("towxname", "群聊"); // 接收消息的群聊名称  

        // 发送消息到微信服务器  
        String response = sendRequest(URL + accessToken, params);
        System.out.println("微信服务器返回的消息：" + response);
    }

    private static String getAccessToken() throws Exception {
        // 获取access_token的请求参数  
        Map<String, String> paramsGetToken = new HashMap<>();
        paramsGetToken.put("grant_type", "client_credential");
        paramsGetToken.put("appid", APPID);
        paramsGetToken.put("secret", SECRET);

        // 发送请求获取access_token  
        String responseGetToken = sendRequest("https://api.weixin.qq.com/cgi-bin/token?access_token=", paramsGetToken);
        System.out.println("获取access_token结果：" + responseGetToken);
        return getJsonValue(responseGetToken, "access_token");
    }

    private static String sendRequest(String url, Map<String, String> params) throws Exception {
        StringBuilder sb = new StringBuilder();
        for (Map.Entry<String, String> entry : params.entrySet()) {
            if (sb.length() != 0) {
                sb.append("&");
            }
            sb.append(entry.getKey()).append("=").append(entry.getValue());
        }
        String requestBody = sb.toString();
        URL obj = new URL(url);
        HttpURLConnection conn = (HttpURLConnection) obj.openConnection();
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        conn.setRequestProperty("Content-Length", String.valueOf(requestBody.length()));
        conn.setDoOutput(true);
        conn.getOutputStream().write(requestBody.getBytes());
        conn.getOutputStream().flush();
        conn.getOutputStream().close();
        BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        String inputLine;
        StringBuffer response = new StringBuffer();
        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();
        return response.toString();
    }

    private static String getJsonValue(String json, String key) {
        String value = "";
        try {
            JSONObject jsonObject = new JSONObject(json);
            value = jsonObject.getString(key);
        } catch (JSONException e) {
            throw new RuntimeException(e);
        }

        return value;
    }
}